import Vue from "vue";
import VueRouter from "vue-router";

import routes from "./routes";
import store from "../store/index";

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location) {
	return originalPush.call(this, location).catch(err => err);
};

const router = new VueRouter({
	mode: "hash",
	base: process.env.BASE_URL,
	routes,
	// 页面滚动到指定位置
	scrollBehavior (to, from, savedPosition) {
		// prettier-ignore
		return to.hash ? { selector: to.hash } : { x: 0, y: 0 };
	}
});

router.beforeEach((to, from, next) => {
	if (to.meta && to.meta.title) {
		store.state.title = to.meta.title;
	}

	if (sessionStorage.getItem("isReload")) {
		// 判断跳转地址是否存在访问记录中
		let r = store.state.historyRoutes.find(data => data.path === to.fullPath);
		// 如果跳转的地址不是首页的话，缓存当前页的地址
		to.fullPath != "/" && localStorage.setItem("backUrl", from.fullPath);
		// 跳转非首页和新页面时，store中新增一条访问记录
		if (!r && to.fullPath != "/") {
			store.commit("addHistoryRoute", to);
		}
	}
	next();
});

export default router;
